package com.roamer.service;

import com.roamer.dao.WeatherDao;
import com.roamer.entity.Weather;
import com.roamer.vo.WeatherVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author roamer
 * @version v1.0
 * @date 2020/3/26 13:02
 */
@Slf4j
@Service
public class WeatherService {

    @Resource
    private WeatherDao weatherDao;
    @Resource
    private JuHeWeatherService juheWeatherService;
    @Resource
    private WeatherService weatherService;

    public WeatherVO getCityWeather(String city) {
        // 缓存/聚合API查询
        WeatherVO weatherVO = juheWeatherService.getCityWeather(city);

        if (weatherVO != null) {
            // 入库
            if (weatherVO.getNewFlag()) {
                Weather weather = new Weather();
                weather.setCity(weatherVO.getCity());
                weather.setTemperature(weatherVO.getTemperature());
                weather.setMaxTemperature(weatherVO.getMaxTemperature());
                weather.setMinTemperature(weatherVO.getMinTemperature());
                weather.setWeather(weatherVO.getWeather());
                weather.setCreateDate(weatherVO.getCreateDate());
                // 使用自身的代理来调用，确保事务生效
                // TODO 保存记得save方法加上事务
                weatherService.saveWeather(weather);
                // 设置为已持久化
                weatherVO.setNewFlag(false);
            }
            return weatherVO;
        }
        // 查询库中最后一条
        return weatherDao.getLastWeatherByCity(city);
    }

    public void saveWeather(Weather weather) {
        weatherDao.save(weather);
    }
}
